import { observable, action, computed } from 'mobx';
import {Tools, Bubble } from 'weaver-mobile';
import { Reply, CKRichText } from 'weaver-mobile-page';
import {getDeviceInfo} from '../../util/jemUtil';
import * as api from '../../apis/sign';
import BaseStore from '../BaseStore';
import moment from 'moment';

const getLabel = Tools.getLabel;
const CKRichEditor = CKRichText.CKRichEditor;

class OutSignRouteStore extends BaseStore{
    //#region CKEditor设置
    @observable ckStore = new CKRichEditor.Store({ initEndCallback: () => {//ckEditor设置
        const { editor } = this.ckStore;
        editor.on('focus', () => {
            this.hideReply();
        }); // onFocus时关闭reply组件
        // this.ckStore.focus('first'); // 获取焦点
    }});
    //#endregion

    //#region 回复组件Plus设置
    @observable replyStore = new Reply.Store({ getAttachList: () => (//回复组件Plus设置
        new Promise(resolve => {
            resolve(
                {
                    attachList: [
                        {
                            key: 'crm', // 字符串
                            type: 'browser',
                            path: '/outSignV2/sign/browser',
                            config: {
                                type: 7,
                                isSingle: false,
                                hasAdvanceSerach: true,
                            },
                            iconType: 'customer',
                            iconBgColor: '#E87E58',
                            text: getLabel('136','客户'),
                        },
                    ]
                }
            )
        })
    )});

    //reply config
    @computed get leftConfig(){
        const config = [
            { type: 'voice' },
            { type: 'blog-tupian'},
        ]
        const {hasCrmModule} = this.baseInfo;
        hasCrmModule && config.push({ type: 'tianjia'});
        return config;
    }

    otherParams = {};

    hideReply = () => {
        this.replyStore.setState({ activeKey: '' });
    }

    onSpeechChange = datas => {
        this.insertHtml(`<span>${datas}</span>`);
    }

    insertHtml = (...args) => {
        this.ckStore.insertHtml(...args);
    }

    @action clearReplyData = () => {
        this.otherParams = {};
    }

    @action setOtherParams = (k, v) => {
        if(k == 'crm'){
            let ids = v.reduce((arr, d) => {
                arr.push(d.id);
                return arr;
            }, []).join(',');
            this.otherParams[k] = ids;
        }
    }
    //#endregion

    //#region 初始化
    @observable _outSignStoreV2;
    @computed get outSignStoreV2(){return this._outSignStoreV2}
    set outSignStoreV2(v){this._outSignStoreV2 = v}

    get currTime(){return this.outSignStoreV2.currTime || moment()}
    get baseInfo(){return this.outSignStoreV2.baseInfo || {}}
    get locationInfo(){return this.outSignStoreV2.currentPosition || {}}
    get outSignSetting(){return this.outSignStoreV2.outSignSetting || {}}

    get remarkRequire(){return this.outSignSetting.remark == '1'}
    get photoRequire(){return this.outSignSetting.photo == '1'}
    get showCompanyName(){return this.outSignSetting.showCompanyName == '1'}

    @action init = () => {
        this.clearReplyData();
        this.replyStore.doClear();
    }
    //#endregion

    //#region 外勤打卡
    @action punchOutButton = async callback => {
        const remark = this.ckStore.getData();
        const {imgList} = this.replyStore.getDatas();
        const fileids = imgList.map(d => d.fileid).join(',');

        let flag = true;
        if(this.remarkRequire && remark.length == 0){
            Bubble.error(getLabel('514419','请填写备注!'));
            flag = false;
        }
        if(this.photoRequire && fileids.length == 0){
            Bubble.error(getLabel('512795','请上传照片!'));
            flag = false;
        }

        if(!flag)
            return;

        const outSignRange = await api.getOutButtonRange();
        if(outSignRange.status != '1'){
            Bubble.error(outSignRange.message);
            return;
        }

        this.Toast.loading('loading', 0);
        const deviceInfo = await getDeviceInfo();

        const {name = '', address, longitude, latitude} = this.locationInfo;
        let addr = address;
        if(this.showCompanyName)
            addr = `${name}${address}`;
        const {outsidesign, signSection} = outSignRange;
        const params = {
            remark,
            address: addr,
            longitude,
            latitude,
            fileids,
            signSection,
            outsidesign,
            ...this.otherParams,
            deviceInfo: JSON.stringify(deviceInfo),
            browser: this.browserType
        }
        const data = await api.punchOutButton(params);
        if(data.status === '1'){
            let msg = getLabel('504568','外勤签到成功');
            if(data.message != null && data.message.trim() != '')
                msg += `,${data.message}`;
            Bubble.success(msg);
            callback && callback();
            this.outSignStoreV2.initialPage = 2;
        }else{
            Bubble.error(data.message);
        }
        this.Toast.hide();
    }
    //#endregion
}

export const outSignRouteStore = new OutSignRouteStore(); 